from typing import List
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from mooc.api import deps
from mooc.crud.crud_admin import admin
from mooc.schemas.admin import Admin, AdminCreate, AdminUpdate


admin_router = APIRouter()
@admin_router.get("/", response_model=List[Admin])
def read_admins(
    db: Session = Depends(deps.get_db),
    # 添加当前用户验证依赖
    current_user: Admin = Depends(deps.get_current_user),
    skip: int = 0,
    limit: int = 100,):
    """
    获取管理员列表
    需要登录权限
    """
    admins = admin.get_multi(db, skip=skip, limit=limit)
    return admins

@admin_router.post("/", response_model=Admin)
def create_admin(
    *,
    db: Session = Depends(deps.get_db),
    # 添加超级管理员验证依赖
    # current_user: Admin = Depends(deps.get_current_superuser),
    admin_in: AdminCreate,
):
    """
    创建新管理员
    需要超级管理员权限
    """
    admin_obj = admin.get_by_username(db, username=admin_in.username)
    if admin_obj:
        raise HTTPException(
            status_code=400,
            detail="Username already registered"
        )
    return admin.create(db, obj_in=admin_in)

@admin_router.put("/{id}", response_model=Admin)
def update_admin(
    *,
    db: Session = Depends(deps.get_db),
    # 添加超级管理员验证依赖
    current_user: Admin = Depends(deps.get_current_superuser),
    id: int,
    admin_in: AdminUpdate,
):
    """
    更新管理员信息
    需要超级管理员权限
    """
    admin_obj = admin.get(db, id=id)
    if not admin_obj:
        raise HTTPException(
            status_code=404,
            detail="Admin not found"
        )
    return admin.update(db, db_obj=admin_obj, obj_in=admin_in)

@admin_router.delete("/{id}", response_model=Admin)
def delete_admin(
    *,
    db: Session = Depends(deps.get_db),
    # 添加超级管理员验证依赖
    current_user: Admin = Depends(deps.get_current_superuser),
    id: int,
):
    """
    删除管理员
    需要超级管理员权限
    """
    admin_obj = admin.get(db, id=id)
    if not admin_obj:
        raise HTTPException(
            status_code=404,
            detail="Admin not found"
        )
    return admin.delete(db, id=id)

# 添加获取当前用户信息的接口
@admin_router.get("/me", response_model=Admin)
def read_user_me(
    current_user: Admin = Depends(deps.get_current_user),
):
    """
    获取当前登录用户信息
    """
    return current_user